package injection;

import domain.User;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;

/**
 * 有多个同类型的 Bean 时，默认注入有 primary 修饰的 Bean
 * 没有被 primary 修饰的，需要使用 @Qualifier 指定名称
 * @author jackcfan
 * @date 2021/9/18
 */
@Configuration
public class QualifierAnnotationInjection {
    @Autowired
    User user;

    @Autowired
    @Qualifier("superUser")
    User superUser;

    @Test
    public void test(){
        // 注解 + xml 配置文件
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 1.注册注解 Bean
        applicationContext.register(this.getClass());

        // 2.读取 xml 配置文件
        // AnnotationConfigApplicationContext 实现了注册中心接口
        // XmlBeanDefinitionReader(BeanDefinitionRegistry registry)
        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(applicationContext);

        // 加载 xml 资源，解析并生成 BeanDefinition
        beanDefinitionReader.loadBeanDefinitions("dependency-setter-injection.xml");

        applicationContext.refresh();

        QualifierAnnotationInjection qualifier = applicationContext.getBean(QualifierAnnotationInjection.class);

        System.out.println("user:"+qualifier.user);
        System.out.println("superUser:"+qualifier.superUser);

        applicationContext.close();
    }
}
